package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.vilyever.drawingview.DrawingView;
import com.vilyever.drawingview.brush.drawing.CircleBrush;
import com.vilyever.drawingview.brush.drawing.EllipseBrush;
import com.vilyever.drawingview.brush.drawing.IsoscelesTriangleBrush;
import com.vilyever.drawingview.brush.drawing.LineBrush;
import com.vilyever.drawingview.brush.drawing.PenBrush;
import com.vilyever.drawingview.brush.drawing.PolygonBrush;
import com.vilyever.drawingview.brush.drawing.RectangleBrush;
import com.vilyever.drawingview.brush.drawing.RightAngledTriangleBrush;
import com.vilyever.drawingview.brush.drawing.RoundedRectangleBrush;
import com.vilyever.drawingview.brush.drawing.ShapeBrush;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.PolygonAdapter;
import flc.ast.bean.PolygonBean;
import flc.ast.databinding.ActivityDrawBinding;
import flc.ast.dialog.ColorDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.container.StkLinearLayout;

public class DrawActivity extends BaseAc<ActivityDrawBinding> {


    private String mSelectColor;
    private PenBrush mPenBrush;
    private List<PolygonBean> mPolygonBeanList = new ArrayList<>();
    private PolygonAdapter mPolygonAdapter;
    private int mSelectPolygonPos;
    private ShapeBrush mSelectBrush;
    private int paintWidth = 15;//画笔宽度
    private int eraserWidth = 15;//橡皮擦宽度
    private int tmpPos = 0;//形状选择下标
    private Dialog mySaveDialog;
    private SeekBar seekBar;
    private TextView textView;
    private StkLinearLayout llPicSaveSuc;


    @Override
    protected int onCreate() {
        return R.layout.activity_draw;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivDrawBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mSelectColor = "#000000";
        mSelectPolygonPos = 0;
        mSelectBrush = PolygonBrush.defaultBrush();

        mDataBinding.ivDrawSave.setOnClickListener(this);
        mDataBinding.ivDrawSelectColor.setOnClickListener(this);
        mDataBinding.ivDrawPaint.setOnClickListener(this);
        mDataBinding.ivDrawEraser.setOnClickListener(this);
        mDataBinding.ivDrawRevocation.setOnClickListener(this);
        mDataBinding.ivDrawRecover.setOnClickListener(this);
        mDataBinding.ivDrawPolygon.setOnClickListener(this);

        mDataBinding.rvPaintPolygon.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mPolygonAdapter = new PolygonAdapter();
        mDataBinding.rvPaintPolygon.setAdapter(mPolygonAdapter);
        mPolygonAdapter.setOnItemClickListener(this);
        mDataBinding.drawingView.setUndoRedoStateDelegate(new DrawingView.UndoRedoStateDelegate() {
            @Override
            public void onUndoRedoStateChange(DrawingView drawingView, boolean canUndo, boolean canRedo) {
                if (canUndo) {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.awqianc);
                } else {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.awhch);
                }
                if (canRedo) {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.awangqianchehui);
                } else {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.awanghouc);
                }
            }
        });
        //保存弹框
        saveDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDrawSelectColor:  // 选择颜色
                ColorDialog colorDialog = new ColorDialog(mContext);
                colorDialog.setListener(new ColorDialog.IListener() {
                    @Override
                    public void onClickConfirm(String color) {
                        mSelectColor = color;
                        mPenBrush.setColor(Color.parseColor(mSelectColor));
                        mSelectBrush.setColor(Color.parseColor(mSelectColor));
                        mDataBinding.crlColorBg.setColor(Color.parseColor(mSelectColor));
                    }
                });
                colorDialog.show();
                break;
            case R.id.ivDrawPaint://画笔
                clearSelection();
                mDataBinding.ivDrawPaint.setImageResource(R.drawable.ahuabb);
                mPenBrush.setIsEraser(false);
                mDataBinding.drawingView.setBrush(mPenBrush);
                mDataBinding.seekbarPaint.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawEraser://橡皮擦
                clearSelection();
                mDataBinding.ivDrawEraser.setImageResource(R.drawable.axiangvpcxz);
                mPenBrush.setIsEraser(true);
                mSelectBrush.setIsEraser(true);
                mDataBinding.seekbarEraser.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawPolygon://多边形
                clearSelection();
                mDataBinding.ivDrawPolygon.setImageResource(R.drawable.axiangzz);
                mDataBinding.llPaintPolygon.setVisibility(View.VISIBLE);
                break;
            case R.id.ivDrawRevocation://撤回
                mDataBinding.drawingView.undo();
                break;
            case R.id.ivDrawRecover://复原
                mDataBinding.drawingView.redo();
                break;
            case R.id.ivDrawSave://保存
                saveImg();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mPolygonAdapter.getItem(tmpPos).setSelected(false);
        mPolygonAdapter.notifyItemChanged(tmpPos);
        tmpPos = position;
        mPolygonAdapter.getItem(position).setSelected(true);
        mPolygonAdapter.notifyItemChanged(position);
        mSelectBrush = mPolygonAdapter.getItem(position).getShapeBrush();
        mSelectBrush.setColor(Color.parseColor(mSelectColor));
        mSelectBrush.setSize(15);
        mDataBinding.drawingView.setBrush(mSelectBrush);
    }

    @Override
    protected void initData() {
        //初始化画笔
        initPen();
        mPolygonBeanList.add(new PolygonBean(PolygonBrush.defaultBrush(), R.drawable.amoren));
        mPolygonBeanList.add(new PolygonBean(RectangleBrush.defaultBrush(), R.drawable.azhenfangx));
        mPolygonBeanList.add(new PolygonBean(IsoscelesTriangleBrush.defaultBrush(), R.drawable.asanjiaox));
        mPolygonBeanList.add(new PolygonBean(CircleBrush.defaultBrush(), R.drawable.ayuanx));
        mPolygonBeanList.add(new PolygonBean(EllipseBrush.defaultBrush(), R.drawable.atuoyuan));
        mPolygonBeanList.add(new PolygonBean(RoundedRectangleBrush.defaultBrush(), R.drawable.azhijsjx));
        mPolygonBeanList.add(new PolygonBean(RightAngledTriangleBrush.defaultBrush(), R.drawable.azhijiaosjx));
        mPolygonBeanList.add(new PolygonBean(LineBrush.defaultBrush(), R.drawable.azhixian));

        mPolygonBeanList.get(tmpPos).setSelected(true);

        mPolygonAdapter.setList(mPolygonBeanList);
    }

    //初始化画笔
    private void initPen() {
        mPenBrush = PenBrush.defaultBrush();
        mPenBrush.setColor(Color.parseColor(mSelectColor));//默认画笔颜色
        mPenBrush.setSize(15);//默认画笔大小
        mDataBinding.drawingView.setBrush(mPenBrush);
        //设置画笔大小
        mDataBinding.seekbarPaint.setMax(50);
        mDataBinding.seekbarPaint.setProgress(5);
        mDataBinding.seekbarPaint.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                mPenBrush.setSize(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //设置橡皮擦大小
        mDataBinding.seekbarEraser.setMax(50);
        mDataBinding.seekbarEraser.setProgress(5);
        mDataBinding.seekbarEraser.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                eraserWidth = 5 + i * 2;
                mPenBrush.setSize(eraserWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //保存图片
    private void saveImg() {
        seekBar.setVisibility(View.VISIBLE);
        llPicSaveSuc.setVisibility(View.GONE);
        textView.setText(getString(R.string.pic_save_ing));
        mySaveDialog.show();
        seekBar.setProgress(new Random().nextInt(60));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.drawingView);
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        //保存到创作中心
                        String filePath = FileUtil.generateFilePath(Content.myDraw, ".png");
                        ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        textView.setText(getString(R.string.pic_save_suc));
                        seekBar.setVisibility(View.GONE);
                        llPicSaveSuc.setVisibility(View.VISIBLE);
                    }
                });
            }
        }, 1000);
    }

    private void clearSelection() {
        mDataBinding.seekbarPaint.setVisibility(View.GONE);
        mDataBinding.seekbarEraser.setVisibility(View.GONE);
        mDataBinding.llPaintPolygon.setVisibility(View.GONE);
        mDataBinding.ivDrawPaint.setImageResource(R.drawable.ahb);
        mDataBinding.ivDrawEraser.setImageResource(R.drawable.axpc);
        mDataBinding.ivDrawPolygon.setImageResource(R.drawable.adbx);
    }

    //保存弹框
    private void saveDialog() {
        mySaveDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_pic_save, null);
        mySaveDialog.setContentView(inflate);
        mySaveDialog.setCancelable(true);
        Window dialogWindow = mySaveDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        seekBar = inflate.findViewById(R.id.sbProgress);
        textView = inflate.findViewById(R.id.tvPicSaveTitle);
        llPicSaveSuc = inflate.findViewById(R.id.llPicSaveSuc);
        TextView tip = inflate.findViewById(R.id.tvDialogPicSaveTip);
        tip.setText(getString(R.string.draw_save_tip));
    }

}